package upload

import (
	"bytes"
	"encoding/json"
	"github.com/panjf2000/ants/v2"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
	"strings"
	"time"
)

const (
	TIME_FORMAT = "2006-01-02"
)

type Config struct {
	Size                int    `json:"size"`
	UploadPath          string `json:"uploadPath"`
	Port                string `json:"port"`
	Url                 string `json:"url"`
	Debug               bool   `json:"debug"`
	UploadUrl           string `json:"uploadUrl"`
	Group               string `json:"group"`
	IsAuthentication    bool   `json:"isAuthentication"`
	AuthenticationField string `json:"authenticationField"`
	AuthenticationUrl   string `json:"authenticationUrl"`
}

var ConfigJson = &Config{}

var Pool = &ants.Pool{}

func init() {

	bytes, err := ioutil.ReadFile("./config.json")
	if err != nil {
		panic("读取json文件失败")
	}
	err = json.Unmarshal(bytes, ConfigJson)
	if err != nil {
		panic("解析数据失败")
	}
	log.Println("是否用Debug模式 ", ConfigJson.Debug, "Debug模式下会自动关闭认证功能")
	if !ConfigJson.Debug {
		//debug模式认证模式无效
		// 已 只写入文件|没有时创建|文件尾部追加 的形式打开这个文件
		logFile, err := os.OpenFile(`./log.txt`, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			panic("日志文件生成失败")
		}
		// 设置存储位置
		log.SetOutput(logFile)
	}
	log.Println("端口 ", ConfigJson.Port, " 上传真实路径: ", ConfigJson.UploadPath, " 线程池: ", ConfigJson.Size)
	Pool, _ = ants.NewPool(ConfigJson.Size)
}

func MatchingPath(url string) string {
	strArr := strings.Split(url, "/")
	bt := GetConfigPath()
	for index, value := range strArr {
		if index < len(strArr)-1 {
			bt.WriteString(value)
			bt.WriteString("/")
		} else {
			bt.WriteString(value)
		}
	}
	realPath := bt.String()
	return realPath
}
func GetConfigPath() bytes.Buffer {
	var bt bytes.Buffer
	bt.WriteString(ConfigJson.UploadPath)
	bt.WriteString("/")
	return bt
}

func GetConfigGroupPath() bytes.Buffer {
	bt := GetConfigPath()
	bt.WriteString(ConfigJson.Group)
	bt.WriteString("/")
	return bt
}

func GetConfigGroupUrl() bytes.Buffer {
	var bt bytes.Buffer
	bt.WriteString(ConfigJson.Url)
	bt.WriteString("/")
	bt.WriteString(ConfigJson.Group)
	bt.WriteString("/")
	return bt
}
func GetPath() (string, string) {
	configPath := GetConfigGroupPath()
	time := time.Now().Format(TIME_FORMAT)
	realPath := configPath.String() + time + "/"
	configUrl := GetConfigGroupUrl()
	url := configUrl.String() + time + "/"
	return realPath, url
}
func GetUploadUrl() string {

	return ConfigJson.UploadUrl
}

func GetImgType(fileName string) string {
	expr := path.Ext(fileName)
	switch expr {
	case ".jpg", ".jpeg", ".png":
		return expr
	default:
		panic("目前只支持 jpg png格式")
	}
}

func CreateImgType(expr string, w http.ResponseWriter, img *image.NRGBA) {
	switch expr {
	case ".jpg", ".jpeg":
		jpeg.Encode(w, img, nil)
	case ".png":
		png.Encode(w, img)
	case ".gif":
		gif.Encode(w, img, nil)
	default:
		panic("目前只支持 jpg png格式")
	}
}
